<template>
  <div class="tattoo-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>产品列表</span>
		  
          <el-button type="primary" @click="handleAdd">新增产品</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="产品标题">
          <el-input v-model="searchForm.title" placeholder="请输入产品标题" clearable />
        </el-form-item>
		<el-form-item label="产品分类">
          <el-select v-model="searchForm.tattoo_id" placeholder="请选择产品分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
	
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
		:cell-style="{ textAlign: 'center' }"
      >
        <el-table-column prop="tattoo_id" label="ID"  width="80" align="center"  />
        <el-table-column prop="title" width="120" label="产品标题" align="center"  />
        <el-table-column label="封面图" align="center" >
          <template #default="{ row }">
            <el-image
              style="width: 80px; height: 80px;border-radius: 10px;"
              :src="`http://bacai.byjx.shop`+row.logo"
              :preview-src-list="[row.logo]"
              fit="cover"
              preview-teleported
              hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column label="图集" width="700" align="center" >
          <template #default="{ row }">
			 <div class="image-gallery">
                <el-image
                  v-for="(img, index) in JSON.parse(row.image)"
                  :key="index"
                  style="width: 100px; height: 100px; margin: 5px;border-radius: 10px;"
                  :src="`http://bacai.byjx.shop`+ img.url"
                  :preview-src-list="getImageList(row.image)"
                  fit="cover"
                  preview-teleported
                  hide-on-click-modal
                />
              </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="80" align="center" >
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80"  align="center" />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_del ? 'danger' : 'success'">
              {{ row.is_del ? '已删除' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center" >
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
    >
      <el-form :model="formData" label-width="120px">
        <el-form-item label="产品标题">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="产品分类">
          <el-select v-model="formData.tattoo_id" placeholder="请选择产品分类">
            <el-option
              v-for="(item,index) in categoryOptions"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图">
			<Uploadimg :limit="1" v-model="formData.logo" :value="formData.logo" @upload="onUpload" />
        </el-form-item>
        <el-form-item label="图集">
			<el-upload
				action="/admin/upload/file"
				list-type="picture-card"
				:file-list="fileList"
				:on-success="handleUploadSuccess"
				:on-remove="handleRemove"
				:before-upload="beforeUpload"
				:limit="9"
				multiple
			>
				<el-icon><Plus /></el-icon>
				<template #file="{ file }">
				<div class="image-item">
					<img class="el-upload-list__item-thumbnail" :src="`http://bacai.byjx.shop`+ file.url" :alt="file.name" />
					<span class="el-upload-list__item-actions">
					<el-button
						type="danger"
						icon="Delete"
						circle
						@click.stop="handleRemove(file)"
					/>
					</span>
				</div>
				</template>
			</el-upload>
			<!-- <Uploadimg :limit="9" v-model="formData.images" :value="formData.images" @upload="onUploads" /> -->
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="formData.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.sort" :min="0" />
        </el-form-item>
        <el-form-item label="产品描述">
          <el-input v-model="formData.content" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed,defineAsyncComponent } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import {getList,Tattoo,save,edit,del} from '/@/api/TattooList/index'
import { Plus,Delete } from '@element-plus/icons-vue'
const Uploadimg = defineAsyncComponent(() => import('/@/components/Upload/singleImage.vue'));


// 类型定义
interface TattooItem {
  id: number
  tattoo_id: number
  title: string
  sort: number
  created_at: string
  is_del: number
  content: string
  update_at: string
  image: string // 图集，多个图片URL用逗号分隔
  logo: string // 封面图
  price: number
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

interface SearchForm {
  title: string,
}

const props = defineProps({
  // 接收字符串形式的初始值（编辑时从后端获取）
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

// 组件内部维护的文件列表（符合Element Plus格式）
const fileList = ref<UploadUserFile[]>([])

// 将字符串转换为标准fileList格式
const initFileList = (urls: string[]) => {
  return urls.filter(Boolean).map((url, index) => ({
    uid: `${Date.now()}-${index}`,
    name: `image-${index}.jpg`,
    url: url,
    status: 'success' as const
  }))
}

// 初始化（编辑时调用）
const initUploader = () => {
  fileList.value = initFileList(props.modelValue.split(','))
}

// 上传成功处理
const handleUploadSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // 假设后端返回 { code: 200, data: { url: string } }
  console.log('收拾收拾',response?.url)
  if (response?.url) {
    fileList.value.push({
      uid: uploadFile.uid,
      name: uploadFile.name,
      url: response.url,
      status: 'success'
    })
    updateModelValue()
  }
}

// 删除图片处理
const handleRemove: UploadProps['onRemove'] = (file) => {
  fileList.value = fileList.value.filter(item => item.uid !== file.uid)
  updateModelValue()
}
// 更新v-model值（转换为逗号分隔字符串）
const updateModelValue = () => {
  const imageUrls = fileList.value
    .filter(file => file.status === 'success')
    .map(file => file.url)
    .filter(Boolean)
  
//   emit('update:modelValue', imageUrls.join(','))
  return imageUrls.join(',')
}

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}



// 数据状态
const tableData = ref<TattooItem[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增产品')
const formData = reactive<Partial<TattooItem>>({
  title: '',
  tattoo_id: null,
  price: 0,
  sort: 0,
  content: '',
  logo: '',
  image: '',
  images:[]
})

// 上传相关
const galleryFileList = ref<UploadUserFile[]>([])

// 分页配置
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const onUploads = (data:String) => {
	const list = []
	list.push(data)
	formData.images.push(data)
	formData.image = formData.images.join(',')
	console.log('图片上传',formData)


}

const onUpload = (data:String) => {
	
	formData.logo = data

	
}
// 搜索表单
const searchForm = reactive<SearchForm>({
  title: '',
})

// 模拟分类选项
const categoryOptions = ref([])

// 将图集字符串转换为数组
const getImageList = (imageStr: string) => {
  const list = []
  const data = JSON.parse(imageStr)
  data.forEach((item) => {
	list.push(item.url)
  })
  return list
}

// 生命周期钩子
onMounted(() => {
  fetchData()
  TattooData()
})


const TattooData = async () => {
	const res = await Tattoo()
	console.log('大大大',res)
	if(res.code === 200) {
		categoryOptions.value = res.data
	}

}
// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    // 这里替换为实际的API调用
    const res = await getList({
      page: pagination.currentPage,
      limit: pagination.pageSize,
      ...searchForm
    })
	if(res.code === 200) {
		tableData.value  = res.data	
        pagination.total = res.total

	}
  
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.tattoo_id = null
  handleSearch()
}

// 新增产品
const handleAdd = () => {
  dialogTitle.value = '新增产品'
  Object.assign(formData, {
    title: '',
    tattoo_id: null,
    price: 0,
    sort: 0,
    content: '',
    logo: '',
    image: ''
  })
  galleryFileList.value = []
  dialogVisible.value = true
}

// 编辑产品
const handleEdit = (row: TattooItem) => {
  dialogTitle.value = '编辑产品'
  Object.assign(formData, row)
  dialogVisible.value = true
  fileList.value = JSON.parse(row.image)
  console.log('打印数组',fileList.value)
}

// 删除产品
const handleDelete = (row: TattooItem) => {
  ElMessageBox.confirm('确定要删除该产品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里替换为实际的API调用
      const res =  await del(row.id)
	  if(res.code === 200) {
		ElMessage.success('删除成功')
		fetchData()
	  }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = async () => {
  try {
    // 这里替换为实际的API调用
    // if (formData.id) {
    //   await updateTattoo(formData)
    // } else {
    //   await createTattoo(formData)
    // }
	if(dialogTitle.value == '新增产品') {
		formData.image = JSON.stringify(fileList.value)
		const res = await save(formData)
	} else {
		formData.image = JSON.stringify(fileList.value)
		console.log('67867',JSON.stringify(fileList.value))

		const res = await edit(formData)
	}
	
    ElMessage.success(dialogTitle.value + '成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error(dialogTitle.value + '失败')
    console.error(error)
  }
}

</script>

<style scoped>

.image-item {
  position: relative;
  width: 100%;
  height: 100%;
}

.el-upload-list__item-actions {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .el-upload-list__item-actions {
  opacity: 1;
}
.tattoo-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  max-height: 500px;
  overflow-y: auto;
}
</style>